package com.gome.axwl.aoc.web.controller.mq.consumer;


import com.cloudcache.client.cache.exceptions.CloudCacheConnectionException;
import com.cloudzone.cloudmq.api.open.base.Action;
import com.cloudzone.cloudmq.api.open.base.ConsumeContext;
import com.cloudzone.cloudmq.api.open.base.Msg;
import com.gome.axwl.aoc.common.util.BeanJsonUtil;
import com.gome.commons.core.ErrorCode;
import com.gome.commons.core.ResultData;
import com.gome.commons.serialization.SerializationService;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;


/**
 *  mq消费者基类
 * @author yinyuxin@gome.com.cn
 * @param <T>
 */
public abstract class AbstractConsumer<T> implements Consumer<T> {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private SerializationService serializationService;

    @Override
    public Action consume(Msg msg, ConsumeContext context, Class<T> msgObjectClass) {
        try {
            byte[] data = msg.getBody();
            T message = serializationService.deserialize(data, msgObjectClass);
            ResultData<?> resultData = processBusinessLogic(message);
            if (resultData == null || !Objects.equals(ErrorCode.SUCCESS,resultData.getCode())) {
                logger.error("消费到axwl-aoc的mq消息,执行具体消费业务出现异常。消费体{},业务接口返回{}", BeanJsonUtil.obj2String(message), BeanJsonUtil.obj2String(resultData));
                return Action.ReconsumeLater;
            }
            return Action.CommitMessage;
        } catch (Exception e) {
            logger.error("消费到axwl-aoc的mq消息,反序列化消息体出现异常:{}",ExceptionUtils.getFullStackTrace(e));
            if (e instanceof CloudCacheConnectionException) {
                return Action.ReconsumeLater;
            }
            return Action.CommitMessage;
        }
    }

    /**
     * 具体的消费 单独写类继承来实现此方法
     * @param t
     * @return
     */
    public abstract ResultData<?> processBusinessLogic(T t);
}
